package com.zsy.fliter;

import com.alibaba.fastjson.JSON;
import com.zsy.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFliter implements Filter {
    //uri路径匹配器
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转为子类，需要使用子类的特殊方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取访问的uri
        String uri = request.getRequestURI();
        //定义一些可以放行的uri
        String[] uris = {
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                //需要将Swagger及Knife4j相关的静态资源直接放行，无需登录即可访问，否则就需要登录之后，才可以访问接口文档的页面。
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        log.info("===========过滤器启动===========");
        //定义一个方法比对uri
        Boolean flog = checkUri(uris, uri);
        if (flog) {
            filterChain.doFilter(request, response);
            return;
        }
        //判断登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }
        //判断是否登录
        Object employee = request.getSession().getAttribute("result");
        if (employee != null) {
            filterChain.doFilter(request, response);
            return;
        }
        //由于这里不是controller需要自己手动转为json字符串
        String notlogin = JSON.toJSONString(R.error("NOTLOGIN"));
        //由于没用登录返回错误信息，回到登录界面
        response.getWriter().write(notlogin);
    }

    private Boolean checkUri(String[] uris, String uri) {
        for (String s : uris) {
            if (antPathMatcher.match(s, uri)) {
                return true;
            }
        }
        return false;

    }
}
